package com.yangtao.framework.ddd;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Author: 杨涛
 * Date: 11-7-12
 * Time: 上午10:32
 */
public abstract class AbstractDomainModel {
	private Logger logger = LoggerFactory.getLogger(getClass());

	//--------和VO之间的转换--------//

	/**
	 * @return
	 */
	public Object toVO() {
		return null;
	}

	public void fromVO(Object vo) {

	}

	//----------和PO之间的转换---------//
	public Object toPO() {
		return null;
	}

	public void fromPO(Object po) {

	}

	//-----------属性-----------------//




	//----------方法-----------------//




	//------------事件--------------//
	/**
	 * 事件容器
	 */
	private Map<String, List<EventListener>> EVENT_CONTAINER;

	/**
	 * 订阅事件
	 *
	 * @param topic    事件主题
	 * @param listener 事件监听
	 */
	public void subscribe(String topic, EventListener listener) {
		if (EVENT_CONTAINER == null)
			EVENT_CONTAINER = new HashMap<String, List<EventListener>>();
		if (EVENT_CONTAINER.get(topic) == null)
			EVENT_CONTAINER.put(topic, new ArrayList<EventListener>());
		EVENT_CONTAINER.get(topic).add(listener);
	}

	/**
	 * 事件触发
	 *
	 * @param topic
	 * @param args
	 */
	public void publish(String topic, Object... args) {
		if (EVENT_CONTAINER == null) {
			if (logger.isDebugEnabled()) {
				logger.debug("event container is null");
			}
			return;
		}
		if (CollectionUtils.isEmpty(EVENT_CONTAINER.get(topic))) {
			if (logger.isDebugEnabled()) {
				logger.debug("event for this topic [" + topic + "] is empty");
			}
			return;
		}
		for (EventListener listener : EVENT_CONTAINER.get(topic)) {
			listener.invoke(args);
		}
	}
}
